package com.gears_software.sxdc.dccx.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.IBankFinder;
import com.gears_software.sxdc.dccx.data.finder.IBaseFinder;
import com.gears_software.sxdc.dccx.data.finder.IMemberFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.MemberModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.request.RChongZhiChargeModel;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.orhanobut.logger.Logger;
import com.pingplusplus.android.Pingpp;
import com.sdsmdg.tastytoast.TastyToast;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.NumberFormat;
import java.util.Locale;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by SunMuran on 2017/9/27.
 * 选择充值方式的activity
 */
@EActivity(R.layout.activity_recharge)
public class RechargeActivity extends Activity {
    private static String YOUR_URL = "http://218.244.151.190/demo/charge";
    public static final String CHARGE_URL = YOUR_URL;
    /**
     * 微信支付渠道
     */
    private static final String CHANNEL_WECHAT = "wx";
    /**
     * 支付宝支付渠道
     */
    private static final String CHANNEL_ALIPAY = "alipay";
    public static final boolean LIVEMODE = false;
    @App
    DCCXApplication app;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    TextView tv_zhifubao_icon;
    @ViewById
    TextView tv_weixin_icon;
    @ViewById
    TextView tv_money_count;
    @ViewById
    TextView tv_money_song_count;
    @ViewById
    RadioButton rb_zhifubao;
    @ViewById
    RadioButton rb_weixin;
    @ViewById
    RadioGroup rg_zhifu;
    @ViewById
    Button btn_submit;
    @RestService
    IBankFinder bankFinder;
    @Bean
    GearsErrorHandler errorHandler;
    String priceid;
    String clineIp;
    int chanel = 1;
    MaterialDialogProgress progress;
    RChongZhiChargeModel chongZhiChargeModel = new RChongZhiChargeModel();

    @AfterViews
    void created() {
        bankFinder.setRestErrorHandler(errorHandler);
        progress = new MaterialDialogProgress(this);
        initIconFont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));
        Intent intent = getIntent();
        priceid = intent.getStringExtra("id");
        BigDecimal giveamount = (BigDecimal) intent.getExtras().get("giveamount");
        BigDecimal rechargeamount = (BigDecimal) intent.getExtras().get("rechargeamount");
        tv_money_count.setText(rechargeamount + "");
        tv_money_song_count.setText(giveamount + "");
        GetNetIp();
    }

    void initIconFont() {
        actionbar_title.setText("充值");
        right_icon.setVisibility(View.GONE);
        back_icon.setText(R.string.back_icon);
        back_icon.setTypeface(app.iconfont);
        tv_zhifubao_icon.setTypeface(app.iconfont);
        tv_weixin_icon.setTypeface(app.iconfont);
    }

    @Click
    void btn_submit() {
        progress.show("正在支付...");
        if (rb_zhifubao.isChecked()) {
            chanel = 1;
            initCharge();
        } else if (rb_weixin.isChecked()) {
            chanel = 2;
            initCharge();
        } else {
            TastyToast.makeText(this, "请选择支付方式", app.SHORT, app.WARNING);
        }

    }
    private void initCharge(){
        chongZhiChargeModel.setChannel(chanel);
        chongZhiChargeModel.setClientIp(clineIp);
        chongZhiChargeModel.setStat(1);
        chongZhiChargeModel.setPriceid(priceid);
        getCharge();
    }

    @Background
    void getCharge() {
        ResultModel<String> res = bankFinder.getChongZhiCharge(chongZhiChargeModel);
        showChargeResult(res);
    }

    @UiThread
    void showChargeResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null && !res.getData().equals("")) {
                    String data = res.getData();
                    Pingpp.createPayment(this, data);
                }
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
                if (progress != null) {
                    progress.dismiss();
                }
            }
        }
    }

    /**
     * onActivityResult 获得支付结果，如果支付成功，服务器会收到ping++ 服务器发送的异步通知。
     * 最终支付成功根据异步通知为准
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (progress != null) {
            progress.dismiss();
        }
        btn_submit.setEnabled(true);
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
                if (result != null && !result.equals("")) {
                     /* 处理返回值
                 * "success" - payment succeed
                 * "fail"    - payment failed
                 * "cancel"  - user canceld
                 * "invalid" - payment plugin not installed
                 */
                    if (result.equals("success")) {
                        TastyToast.makeText(this, "充值成功", app.SHORT, app.SUCCESS);
                        this.finish();

                    } else if (result.equals("fail")) {
                        TastyToast.makeText(this, "充值失败", app.SHORT, app.ERROR);
                    } else if (result.equals("cancel")) {
                        TastyToast.makeText(this, "您已取消充值", app.SHORT, app.WARNING);
                    } else if (result.equals("invalid")) {
                        TastyToast.makeText(this, "末能安装应用", app.SHORT, app.WARNING);
                    }

                } else {
                    String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                    String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                    TastyToast.makeText(this, errorMsg + errorMsg, app.SHORT, app.ERROR);
                }

            }
        }
    }


    @Click
    void back_icon() {
        finish();
    }

    /**
     * 获取外网IP地址
     */
    @Background
    void GetNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String line = "";
        try {
            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("{");
                int end = strber.indexOf("}");
                String json = strber.substring(start, end + 1);
                if (json != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        line = jsonObject.optString("cip");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                showResult(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @UiThread
    void showResult(String line) {
        clineIp = line;
    }


}
